import 'package:flutter/material.dart';

class Pageviewkeepalive extends StatefulWidget {
  const Pageviewkeepalive({super.key});

  @override
  State<Pageviewkeepalive> createState() => _PageviewkeepaliveState();
}

//自定义组件
class _PageviewkeepaliveState extends State<Pageviewkeepalive> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Pageviewkeepalive演示')),
      body: PageView.builder(
        scrollDirection: Axis.vertical,
        itemCount: 10,
        itemBuilder: (content, index) {
          return MyContainer(num: index);
        },
      ),
    );
  }
}

class MyContainer extends StatefulWidget {
  final int num;

  const MyContainer({super.key, required this.num});

  @override
  State<MyContainer> createState() => _MyContainerState();
}

class _MyContainerState extends State<MyContainer> with AutomaticKeepAliveClientMixin {
  @override
  Widget build(BuildContext context) {
    print(widget.num);//默认数据没有缓存，每次滑动都会调用build方法
    return Center(
      child: Text(
        '第${widget.num + 1}屏',
        style: Theme.of(context).textTheme.headlineMedium,
      ),
    );
  }
  
  @override
  // TODO: implementwantKeepAlive
  bool get wantKeepAlive => true;  //返回true表示缓存页面
}
